// 注册页

import 'package:flutter/material.dart';

import 'dart:async';
import 'dart:convert';

import '../widget/widget_login_button.dart';
import '../widget/widget_login_textfield.dart';
import '../tools/tools_net.dart';

class PageRegister extends StatefulWidget {
  const PageRegister({super.key});

  @override
  State<PageRegister> createState() => _PageRegisterState();
}

class _PageRegisterState extends State<PageRegister> {
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();
  final _repasswordController = TextEditingController();
  final _codeController = TextEditingController();

  String _base64Str = "";
  String _uuid = "";

  bool _registerOk = false;

  Timer? timer = null;
  @override
  void initState() {
    super.initState();

    refreshCode();

    timer = Timer.periodic(Duration(seconds: 1), (Timer timer) {
      print("定时判断");
      if (_registerOk) {
        Navigator.of(context).pop();
      }
    });
  }

  @override
  void dispose() {
    if (timer != null) {
      timer!.cancel();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[300],
      body: SafeArea(
          child: Center(
        child: Column(
          children: [
            SizedBox(
              height: 50,
            ),
            Icon(
              Icons.account_circle_rounded,
              size: 100,
            ),
            SizedBox(
              height: 50,
            ),
            Text("欢迎注册,请输入您的账号信息!"),
            SizedBox(
              height: 25,
            ),
            WidgetLoginTextfield(
              hintText: "请输入用户名",
              obscureText: false,
              controller: _usernameController,
            ),
            SizedBox(
              height: 10,
            ),
            WidgetLoginTextfield(
              hintText: "请输入密码",
              obscureText: false,
              controller: _passwordController,
            ),
            SizedBox(
              height: 10,
            ),
            WidgetLoginTextfield(
              hintText: "请输入重复密码",
              obscureText: false,
              controller: _repasswordController,
            ),
            SizedBox(
              height: 10,
            ),
            Row(
              children: [
                Expanded(
                  child: WidgetLoginTextfield(
                    hintText: "请输入验证码",
                    obscureText: false,
                    controller: _codeController,
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(right: 20),
                  child: GestureDetector(
                    onTap: refreshCode,
                    child: SizedBox(
                      width: 100,
                      height: 60,
                      child: _base64Str.length > 0 ? Image.memory(base64Decode(_base64Str)) : null,
                    ),
                  ),
                ),
              ],
            ),
            SizedBox(
              height: 10,
            ),
            WidgetLoginButton(
                text: "注册",
                onTap: () {
                  register(context);
                }),
            SizedBox(
              height: 50,
            ),
            Expanded(child: Container()),
            GestureDetector(
              onTap: () {
                login(context);
              },
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text("已注册?"),
                  SizedBox(
                    width: 8,
                  ),
                  Text(
                    "立即登录",
                    style: TextStyle(color: Colors.lightBlue),
                  ),
                ],
              ),
            )
          ],
        ),
      )),
    );
  }

  // 1. 刷新验证码
  refreshCode() {
    print("刷新验证码");
    // 请求验证码图片
    ToolsNet.requestCode().then((String value) {
      var obj = ToolsNet.parseJSON(value);
      _base64Str = obj["img"];
      _uuid = obj["uuid"];
      setState(() {});
    }).onError((e, s) {
      print(e);
      print(s);

      showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text("出错了"),
              content: Text("请检查网络或者联系管理员。"),
              actions: [
                TextButton(
                    onPressed: () {
                      Navigator.pop(context);
                    },
                    child: Text("确定")),
              ],
            );
          });
    });
  }

  // 2 返回登录页面
  login(context) {
    print("登录");
    Navigator.pop(context);
  }

  // 3. 执行用户注册
  register(context) {
    print("注册");

    String username = _usernameController.text;
    String password = _passwordController.text;
    String repassword = _repasswordController.text;
    String code = _codeController.text;

    Map<String, dynamic> m = new Map();
    m["username"] = username;
    m["password"] = password;
    m["repassword"] = repassword;
    m["code"] = code;
    m["uuid"] = _uuid;

    ToolsNet.requestRegister(m).then((value) {
      var obj = ToolsNet.parseJSON(value);
      print(obj);
      if (obj["msg"] == "操作成功") {
        print("操作成功");
        showDialog(
            context: context,
            builder: (BuildContext context) {
              return AlertDialog(
                title: Text("注册成功"),
                content: Text("注册成功，请登录"),
                actions: [
                  TextButton(
                      onPressed: () {
                        Navigator.pop(context);
                        _registerOk = true;
                      },
                      child: Text("确定")),
                ],
              );
            });
      } else {
        print("操作失败");
        _codeController.clear();
        refreshCode();
        // 刷新验证码
        showDialog(
            context: context,
            builder: (BuildContext context) {
              return AlertDialog(
                title: Text("注册失败"),
                content: Text("${obj["msg"]}"),
                actions: [
                  TextButton(
                      onPressed: () {
                        Navigator.pop(context);
                      },
                      child: Text("确定")),
                ],
              );
            });
      }
    });
  }
}

// Future.delayed(Duration(seconds: 2), () {
// Navigator.pop(context);
// });
// Looking up a deactivated widget's ancestor is unsafe.
// At this point the state of the widget's element tree is no longer stable.
// To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.
